#!/usr/bin/env python3
"""
结构化日志示例
演示如何使用统一日志模块记录结构化数据
"""

import asyncio
import time
from unified_logger import AsyncUnifiedLogger, LogLevel


async def structured_logging_demo():
    """结构化日志演示"""
    # 创建日志器实例
    logger = AsyncUnifiedLogger(
        name="structured_demo",
        log_level=LogLevel.DEBUG,
        enable_console=True
    )
    
    try:
        # 启动日志器
        await logger.start()
        
        # 示例1：基本结构化数据
        user_data = {
            "user_id": 12345,
            "username": "alice_wonder",
            "email": "alice@example.com",
            "action": "login",
            "ip": "192.168.1.100"
        }
        
        await logger.info(
            "用户登录成功",
            extra=user_data
        )
        
        # 示例2：业务指标记录
        metrics = {
            "response_time": 245.7,
            "status_code": 200,
            "endpoint": "/api/v1/users",
            "method": "GET",
            "bytes_sent": 1024
        }
        
        await logger.info(
            "API请求完成",
            extra=metrics
        )
        
        # 示例3：错误场景记录
        try:
            # 模拟一个错误
            result = 10 / 0
        except ZeroDivisionError as e:
            error_context = {
                "error_type": type(e).__name__,
                "error_message": str(e),
                "operation": "division",
                "operands": {"numerator": 10, "denominator": 0},
                "trace_id": "req-20250111-001"
            }
            
            await logger.error(
                "计算错误发生",
                extra=error_context,
                stack_info=True  # 包含堆栈信息
            )
        
        # 示例4：性能监控
        start_time = time.time()
        
        # 模拟一些工作
        await asyncio.sleep(0.1)
        
        performance_data = {
            "duration_ms": (time.time() - start_time) * 1000,
            "memory_usage_mb": 128.5,
            "cpu_percent": 15.2,
            "operation": "data_processing"
        }
        
        await logger.debug(
            "性能指标",
            extra=performance_data
        )
        
        # 示例5：批量操作记录
        users = [
            {"id": 1, "name": "Alice", "role": "admin"},
            {"id": 2, "name": "Bob", "role": "user"},
            {"id": 3, "name": "Charlie", "role": "user"}
        ]
        
        for user in users:
            await logger.info(
                "处理用户信息",
                extra={
                    "user_id": user["id"],
                    "username": user["name"],
                    "role": user["role"],
                    "operation": "batch_update"
                }
            )
        
        print("结构化日志演示完成！")
        
    finally:
        # 确保刷新所有日志
        await logger.flush()
        await logger.stop()


if __name__ == "__main__":
    asyncio.run(structured_logging_demo())